package com.gdpu.watermelontimer.timer

import android.content.Context
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.VibrationEffect
import android.os.Vibrator
import android.os.VibratorManager
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.gdpu.watermelontimer.data.PomodoroSession
import kotlinx.coroutines.*
import java.util.*

class PomodoroTimer(private val context: Context) {
    
    private var timerJob = Job()
    private var timerScope = CoroutineScope(Dispatchers.Main + timerJob)
    
    private val _timerState = MutableLiveData<TimerState>()
    val timerState: LiveData<TimerState> = _timerState
    
    private val _currentTime = MutableLiveData<Long>()
    val currentTime: LiveData<Long> = _currentTime
//    进度条的
    private val _progress = MutableLiveData<Float>()
    val progress: LiveData<Float> = _progress
    
    private var currentSession: PomodoroSession? = null
    private var isPaused = false
    private var remainingTime = 0L
    
    // 默认设置
    private var workDuration = 25 * 60 * 1000L // 25分钟
    private var shortBreakDuration = 5 * 60 * 1000L // 5分钟
    private var longBreakDuration = 15 * 60 * 1000L // 15分钟
    private var longBreakInterval = 4 // 每4个番茄钟后长休息
    
    private var completedPomodoros = 0
    private var currentTaskId: Long? = null
    
    private var vibrator: Vibrator? = null
    private var mediaPlayer: MediaPlayer? = null
    
    init {
        _timerState.value = TimerState.IDLE
        _currentTime.value = workDuration
        _progress.value = 1.0f//初始化进度条
        
        // 初始化震动器
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            val vibratorManager = context.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
            vibrator = vibratorManager.defaultVibrator
        } else {
            @Suppress("DEPRECATION")
            vibrator = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
        }
    }
    
    fun startWorkSession(taskId: Long? = null) {
        currentTaskId = taskId
        startSession(PomodoroSession.SessionType.WORK, workDuration)
    }
    
    fun startShortBreak() {
        startSession(PomodoroSession.SessionType.SHORT_BREAK, shortBreakDuration)
    }
    
    fun startLongBreak() {
        startSession(PomodoroSession.SessionType.LONG_BREAK, longBreakDuration)
    }
    
    private fun startSession(sessionType: PomodoroSession.SessionType, duration: Long) {
        // 先取消旧的线程？能这样说吧，防止多协线程叠加
        timerJob.cancel()
        timerJob = Job()
        timerScope = CoroutineScope(Dispatchers.Main + timerJob)
        if (_timerState.value == TimerState.RUNNING) {
            stopTimer()
        }
        remainingTime = duration
        _currentTime.value = remainingTime
        _progress.value = 1.0f//进度条重置
        isPaused = false
        currentSession = PomodoroSession(
            taskId = currentTaskId,
            sessionType = sessionType,
            startTime = System.currentTimeMillis(),
            duration = duration
        )
        _timerState.value = TimerState.RUNNING
        startCountdown()
    }
    
    private fun startCountdown() {
        timerScope.launch {
            while (remainingTime > 0 && !isPaused) {
                delay(1000)
                remainingTime -= 1000//剩余时间
                val session = currentSession ?: return@launch
                _currentTime.value = remainingTime
                _progress.value = remainingTime.toFloat() / session.duration//当前进度！
            }
            
            if (remainingTime <= 0) {
                completeSession()
            }
        }
    }
    
    private fun completeSession() {
        currentSession?.let { session ->
            session.endTime = System.currentTimeMillis()
            session.actualDuration = session.endTime!! - session.startTime
            session.isCompleted = true
            
            if (session.sessionType == PomodoroSession.SessionType.WORK) {
                completedPomodoros++
            }
        }
        
        _timerState.value = TimerState.COMPLETED
        playNotification()
        
        // 自动开始下一个会话
        autoStartNextSession()
        // 关键：完成后重置为IDLE，允许再次点击开始
        _timerState.value = TimerState.IDLE
    }
    
    private fun autoStartNextSession() {
        timerScope.launch {
            delay(1000) // 等待1秒后自动开始
            when {
                currentSession?.sessionType == PomodoroSession.SessionType.WORK -> {
                    if (completedPomodoros % longBreakInterval == 0) {
                        startLongBreak()
                    } else {
                        startShortBreak()
                    }
                }
                currentSession?.sessionType == PomodoroSession.SessionType.SHORT_BREAK -> {
                    startWorkSession(currentTaskId)
                }
                currentSession?.sessionType == PomodoroSession.SessionType.LONG_BREAK -> {
                    startWorkSession(currentTaskId)
                }
            }
        }
    }
    
    fun pauseTimer() {
        if (_timerState.value == TimerState.RUNNING) {
            isPaused = true
            _timerState.value = TimerState.PAUSED
        }
    }
    
    fun resumeTimer() {
        if (_timerState.value == TimerState.PAUSED) {
            isPaused = false
            _timerState.value = TimerState.RUNNING
            startCountdown()
        }
    }
    
    fun stopTimer() {
        timerJob.cancel()
        currentSession?.let { session ->
            session.isInterrupted = true
        }
        _timerState.value = TimerState.IDLE
        _currentTime.value = workDuration
        _progress.value = 1.0f
        currentSession = null
        isPaused = false
    }
    
    fun skipSession() {
        currentSession?.let { session ->
            session.isInterrupted = true
        }
        completeSession()
    }
    
    fun resetTimer() {
        stopTimer()
        startWorkSession(currentTaskId)
    }
    
    private fun playNotification() {
        // 震动提醒
        vibrator?.let { v ->
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                v.vibrate(VibrationEffect.createOneShot(1000, VibrationEffect.DEFAULT_AMPLITUDE))
            } else {
                @Suppress("DEPRECATION")
                v.vibrate(1000)
            }
        }
        
        // 声音提醒
        try {
            mediaPlayer?.release()
            mediaPlayer = MediaPlayer.create(context, android.provider.Settings.System.DEFAULT_NOTIFICATION_URI)
            mediaPlayer?.start()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    
    fun updateSettings(
        workDuration: Long,
        shortBreakDuration: Long,
        longBreakDuration: Long,
        longBreakInterval: Int
    ) {
        this.workDuration = workDuration
        this.shortBreakDuration = shortBreakDuration
        this.longBreakDuration = longBreakDuration
        this.longBreakInterval = longBreakInterval

        // 只要设置了就刷新当前时间
        _currentTime.value = this.workDuration
    }
    
    fun getCurrentSession(): PomodoroSession? = currentSession
    
    fun getCompletedPomodoros(): Int = completedPomodoros
    
    fun cleanup() {
        timerJob.cancel()
        mediaPlayer?.release()
        mediaPlayer = null
    }
    
    enum class TimerState {
        IDLE, RUNNING, PAUSED, COMPLETED
    }
} 